package keke.ai.code.mother.service.security;

import cn.hutool.core.bean.BeanUtil;
import jakarta.annotation.Resource;
import keke.ai.code.mother.exception.BizException;
import keke.ai.code.mother.exception.ErrorCode;
import keke.ai.code.mother.model.auth.MyUserDetail;
import keke.ai.code.mother.model.vo.user.UserVo;
import keke.ai.code.mother.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

public class MyUserDetailService implements UserDetailsService {

    @Resource
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserVo userVo = userService.findUserByUserName(username);

        if(Objects.isNull(userVo)) {
            throw new BizException(ErrorCode.SYSTEM_ERROR, "用户不存在");
        }

        MyUserDetail myUserDetail = new MyUserDetail();

        BeanUtil.copyProperties(userVo, myUserDetail);

        //获取用户角色集合
        String userRole = myUserDetail.getUserRole();
        List<GrantedAuthority> grantedAuthorities = AuthorityUtils.commaSeparatedStringToAuthorityList(userRole);
        myUserDetail.setUserAuthorities(grantedAuthorities);

        return myUserDetail;
    }
}
